<template>
    <el-card shadow="never" class="index">
        <template #header>
            <div class="card_header">
                <b>审批管理</b>
            </div>
        </template>
        <!-- 内容区 -->
        <el-table stripe ref="multipleTableRef" v-loading="loading" :data="tableData" style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" />
            <el-table-column type="index" sortable label="序号" width="60" />
            <el-table-column label="申请人" prop="sname" width="80" />
            <el-table-column label="申请方向" prop="position" width="140" />
            <el-table-column label="文档" prop="doc_path">
                <template #default="scope">
                    <el-link target="_blank" :href="getHref(scope.row.doc_path)">{{ getFileName(scope.row.doc_path) }}
                    </el-link>
                </template>
            </el-table-column>
            <el-table-column label="状态" prop="status" width="100">
                <template #default="scope">
                    <el-tag v-if="scope.row.status" :type="approveStatusConvertToElTagType(scope.row.status)"
                        style="margin-left: 3px;">{{
                                approveStatusConvertToStr(scope.row.status)
                        }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="审批老师" prop="t1name" width="160">
                <template #default="scope">
                    <p>
                        <el-tag effect="plain" type="info">{{ scope.row.t1name }}</el-tag>
                        <el-tag :type="approveStatusConvertToElTagType(scope.row.tstatus)" style="margin-left: 3px;">{{
                                approveStatusConvertToStr(scope.row.tstatus)
                        }}
                        </el-tag>
                    </p>
                </template>
            </el-table-column>
            <el-table-column label="审批老师" prop="t2name" width="160">
                <template #default="scope">
                    <p>
                        <el-tag effect="plain" type="info">{{ scope.row.t2name }}</el-tag>
                        <el-tag :type="approveStatusConvertToElTagType(scope.row.t2status)" style="margin-left: 3px;">{{
                                approveStatusConvertToStr(scope.row.t2status)
                        }}
                        </el-tag>
                    </p>
                </template>
            </el-table-column>
            <el-table-column label="时间" sortable prop="cdate" width="160" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" type="danger" v-if="hasShow(scope.row)"
                        @click="handleApproval(scope.$index, scope.row, false)">驳回
                    </el-button>
                    <el-button size="small" type="success" v-if="hasShow(scope.row)"
                        @click="handleApproval(scope.$index, scope.row, true)">批准
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- <div style="margin-top: 20px">
            <el-pagination background hide-on-single-page :current-page="pageNum" :page-size="pageSize"
                :total="totalNum" @current-change="handlePageChange" layout="prev, pager, next"
                style="margin-bottom:10px;"></el-pagination>
            <el-button type="danger" @click="handleSelectApproval(false)">驳回</el-button>
            <el-button type="success" @click="handleSelectApproval(true)">批准</el-button>
        </div> -->
        <!-- 内容去 end -->
    </el-card>
</template>

<script>
import { useStore } from 'vuex';
import { Picture as IconPicture } from '@element-plus/icons'
import { ElTable, ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref, computed, onBeforeMount, toRaw, getCurrentInstance } from 'vue'

import router from '../../router';
import Icons from '../../components/Icons.vue';
import { approveService } from '../../interfaces/service'


export default {
    components: { IconPicture, ElTable, Icons },
    setup() {
        const { proxy } = getCurrentInstance();

        const store = useStore();

        // 钩子函数
        onBeforeMount(() => {
            loadTableData();
        })

        /**
         * 加载表格数据事件
         */
        const loadTableData = () => {
            let data = {
                "pageSize": pageSize.value,
                "pageNum": pageNum.value,
            };
            var formInlineCondition = toRaw(formInline);
            Object.keys(formInlineCondition).forEach(key => {
                if (formInlineCondition[key]) {
                    data[`conditions[${key}]`] = formInlineCondition[key];
                }
            });
            loading.value = true;
            approveService.getApprovesForTeacher(data)
                .then(res => {
                    loading.value = false;
                    if (res.success) {
                        let list = res.data.list;
                        let total_num = res.data.totalNum;
                        totalNum.value = total_num;
                        tableData.value = list;
                    }
                })
        }

        // 搜索条件
        const formInline = reactive({
            name: '',
            phone: '',
            email: '',
        })

        // 处理搜索按钮
        const handleSearch = () => {
            loadTableData();
        }

        // 多选批准事件
        const handleSelectApproval = (ok) => {
            if (multipleSelection.value && multipleSelection.value.length > 0) {
                let ids = '';
                multipleSelection.value.forEach(item => {
                    if (item.tid == null)
                        ids += item.id + ',';
                });
                const data = { id: ids };
                if (ok) {
                    data.ok = ok;
                }
                approveService.applyApprove(data)
                    .then(res => {
                        if (res.success) {
                            ElMessage.success(ok ? "批准成功" : "驳回成功");
                            loadTableData();
                        }
                    })
            } else {
                ElMessage.info("请先选中一行数据")
            }
        }

        // 添加事件
        const handleAdd = () => {
            router.push({ name: 'StudentApply' })
        }

        // 表格加载状态
        const loading = ref(false)
        //表格实体引用
        const multipleTableRef = ref(null)
        // 表格选中的数据
        const multipleSelection = ref(null)

        // 表格改变事件
        const handleSelectionChange = (val) => {
            // 表格选中的数据
            multipleSelection.value = val
        }

        // 表格数据
        const tableData = ref([]);

        // 本地搜索条件
        const search = ref('')
        const filterTableData = computed(() => {
            tableData.value.filter(
                (data) =>
                    !search.value || data.name.toLowerCase().includes(search.value.toLowerCase())
            )
        })

        const getUserOrder = (row) => {
            const user = store.getters.getUser;
            const tid = user.id;
            const order = tid == row.t1id ? 1 : 2;
            return order;
        }

        const getHref = (href) => import.meta.env.VITE_APP_BASE_API + "/" + href;

        const getFileName = (href) => {
            if(!href) return;
            let index = href.lastIndexOf("/");
            const name = href.substring(index + 1);
            return name;
        }

        // 批准驳回事件
        const handleApproval = (index, row, ok) => {
            const order = getUserOrder(row);
            approveService.applyApprove(row.id, order, ok)
                .then(res => {
                    if (res.success) {
                        ElMessage.success(ok ? "批准成功" : "驳回成功");
                        loadTableData();
                        // if (order === 1) {
                        //     row.status = ok ? "Approving" : "Confuted";
                        // } else {
                        //     row.status2 = ok ? "Approving" : "Confuted";
                        // }
                    } else {
                        console.log({ res });
                    }
                })
        }

        //#region 状态管理

        // 根据状态是否显示操作按钮
        const hasShow = (row) => {
            if (row.status !== 'Approving') {
                return false;
            }

            const order = getUserOrder(row);
            let status = null;
            if (order === 1) {
                status = row.tstatus;
            } else {
                status = row.t2status;
            }
            if (status === 'Approving')
                return true;
            return false;
        }

        // 状态转化为字符状态
        const approveStatusConvertToStr = computed(() => (status) =>
            statusConvertDict['str'][status]
        )

        const statusConvertDict = {
            "str": {
                "": "未知",
                "Approving": "审批中",
                "Approved": "通过",
                "Confuted": "驳回",
                "Cancel": "取消",
            },
            "tagType": {
                "": "",
                "Approving": "",
                "Approved": "success",
                "Confuted": "danger",
                "Cancel": "waring",
            },
        }

        // 状态转化为标签类型
        const approveStatusConvertToElTagType = computed(() => (status) =>
            statusConvertDict['tagType'][status]
        )

        //#endregion


        // 分页组件
        const pageNum = ref(1)
        const pageSize = ref(10)
        const totalNum = ref(10)
        // 当前页改变事件
        const handlePageChange = (n) => {
            pageNum.value = n
            loadTableData()
        }

        return {
            formInline,
            tableData,
            loading,
            multipleSelection,
            multipleTableRef,
            pageNum,
            pageSize,
            totalNum,
            filterTableData,
            approveStatusConvertToElTagType,
            approveStatusConvertToStr,
            handleSearch,
            handleAdd,
            handleApproval,
            handleSelectApproval,
            handleSelectionChange,
            handlePageChange,
            hasShow,
            getHref,
            getFileName,
        }
    }
}
</script>

<style lang="scss" scoped>
.card_header {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.box-card {
    margin-bottom: 50px;
}
</style>
